package com.ljfiction.book.Dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ljfiction.book.MyView.ContainsEmojiEditText;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.activitys.BaseActivity;

import com.ljfiction.book.activitys.PursActivity;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class ToSubcritDialog {
    private Dialog mDialog;
    private Listener listener;
    private ViewHolder viewHolder;
    private Context mContext;
    private BaseQuickAdapter adapter;
    private int[] dataimage = {R.mipmap.xiaolajiaoone, R.mipmap.xiaolajiaotow, R.mipmap.xiaolajiaothree, R.mipmap.xiaolajiaofour, R.mipmap.xiaolajiaofive, R.mipmap.xiaolajiaosex};
    private List<String> dataString = new ArrayList<>();
    private int isgridviewselect = 0;
    private String bookid, bookname, authorId;
    private NoBackgLodDialog noBackgLodDialog;

    public ToSubcritDialog(Context context, String bookid, String bookname, String authorId) {
        mContext = context;
        this.bookid = bookid;
        this.bookname = bookname;
        this.authorId = authorId;
        mDialog = new Dialog(context, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(context).inflate(R.layout.subcrit_dialog, null);
        viewHolder = new ViewHolder(view);
        //将布局设置给Dialog
        mDialog.setContentView(view);
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.width = context.getResources().getDisplayMetrics().widthPixels;
        view.setLayoutParams(layoutParams);
        mDialog.getWindow().setGravity(Gravity.BOTTOM);
        mDialog.getWindow().setWindowAnimations(R.style.AnimBottom);
        mDialog.setCancelable(true);
        intview();
    }

    private void intview() {
        dataString.add("188");
        dataString.add("288");
        dataString.add("588");
        dataString.add("888");
        dataString.add("1888");
        dataString.add("8888");
        viewHolder.subdialogGrideview.setLayoutManager(new GridLayoutManager(mContext, 3));
        viewHolder.subdialogGrideview.setAdapter(adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.geivemoney_item, dataString) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                AutoUtils.autoSize(helper.itemView);
                if (helper.getLayoutPosition() == isgridviewselect) {
                    helper.getView(R.id.backgroud_giveitem).setBackgroundResource(R.drawable.shape_giverewardok);

                } else {
                    helper.getView(R.id.backgroud_giveitem).setBackgroundResource(R.drawable.shape_givereward);
                }
                helper.setImageResource(R.id.image_givemoneyitem, dataimage[helper.getLayoutPosition()]);
                if (helper.getLayoutPosition() == dataString.size() - 1) {
                    helper.getView(R.id.songyilajiao).setVisibility(View.VISIBLE);

                } else {
                    helper.getView(R.id.songyilajiao).setVisibility(View.GONE);

                }
                helper.setText(R.id.text_givemoneyitem, item + "辣椒");
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                isgridviewselect = position;
                adapter.notifyDataSetChanged();
            }
        });
        viewHolder.subdialogyouMoney.setText(String.valueOf(UserManageBean.userBean.getUserMoney()));
        viewHolder.subdialogChongzhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(mContext,PursActivity.class);
                mContext.startActivity(intent);
                thisdismis();
            }
        });
        viewHolder.subdialogDangshangok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!UserManageBean.isLogin(mContext)) {
                    thisdismis();
                    return;
                }
                if (UserManageBean.userBean.getUserMoney() < 188) {
                    Tool.showToast("辣椒不足，快去充值吧", mContext);
                    return;
                }
                toDashang();
            }
        });
        viewHolder.subdialogWhangtesay.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (String.valueOf(s).length() >= 20) {
                    Tool.showToast("字数不能大于20哦", mContext);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                viewHolder.subdialogZinum.setText(viewHolder.subdialogWhangtesay.length() + "/20");
            }
        });
    }

    public void thisdismis() {
        mDialog.dismiss();
    }

    public void show() {
        if (mDialog != null) {
            mDialog.show();
            if (UserManageBean.isLogin()) {
                if (viewHolder != null) {
                    viewHolder.subdialogyouMoney.setText(String.valueOf(UserManageBean.userBean.getUserMoney()));
                }
            }
        }
    }

    public void setListener(Listener listener) {
        this.listener = listener;
        show();
    }

    public interface Listener {
        void subclickok();

        void subnologin();
    }

    private void toDashang() {
        if (StringTool.isEmpty(viewHolder.subdialogWhangtesay.getText().toString())) {
            OkHttpUtils.post(HttpManager.IP + "/user-SpicyiRewardTicket")

                    .params("spicyiTicketCount", dataString.get(isgridviewselect))
                    .params("bookid", bookid)
                    .params("bookName", bookname)
                    .params("authorId", authorId)
                    .execute(new StringCallback() {
                        @Override
                        public void onBefore(BaseRequest request) {
                            super.onBefore(request);
                            if (noBackgLodDialog == null) {
                                noBackgLodDialog = new NoBackgLodDialog(mContext, true);
                            }
                            noBackgLodDialog.show();
                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            noBackgLodDialog.dismis();
                            try {
                                JSONObject json = new JSONObject(s);
                                if (200 == json.getInt("returnCode")) {
                                    Tool.showToast(json.getString("msg"), mContext);
                                   /* toChangeBookData(1);
                                    toDashangDatas();*/
                                    listener.subclickok();
                                    UserManageBean.backgroundRiches(mContext);
                                    thisdismis();
                                } else {
                                    if (400 == json.getInt("returnCode")) {
                                        listener.subnologin();
                                    }
                                    Tool.showToast(json.getString("msg"), mContext);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } else {
            OkHttpUtils.post(HttpManager.IP + "/user-SpicyiRewardTicket")

                    .params("spicyiTicketCount", dataString.get(isgridviewselect))
                    .params("bookid", bookid)
                    .params("bookName", bookname)
                    .params("authorId", authorId)
                    .params("message", viewHolder.subdialogWhangtesay.getText().toString())
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            try {
                                JSONObject json = new JSONObject(s);
                                if (200 == json.getInt("returnCode")) {
                                    Tool.showToast(json.getString("msg"), mContext);
                                    listener.subclickok();
                                    UserManageBean.backgroundRiches(mContext);
                                    thisdismis();
                                } else {
                                    if (400 == json.getInt("returnCode")) {
                                        listener.subnologin();
                                    }
                                    Tool.showToast(json.getString("msg"), mContext);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        }

    }

    class ViewHolder {
        @BindView(R.id.subdialogyou_money)
        TextView subdialogyouMoney;
        @BindView(R.id.subdialog_chongzhi)
        SuperButton subdialogChongzhi;
        @BindView(R.id.subdialog_whangtesay)
        ContainsEmojiEditText subdialogWhangtesay;
        @BindView(R.id.subdialog_zinum)
        TextView subdialogZinum;
        @BindView(R.id.subdialog_grideview)
        RecyclerView subdialogGrideview;
        @BindView(R.id.subdialog_dangshangok)
        SuperButton subdialogDangshangok;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
